import {ResolvedConfig} from "vite";
import * as fs from "fs";

/**
 * 检查是否有引入eruda
 */
const checkErudaImport = (code: string): boolean => {
  return code.includes('import eruda') || code.includes("require('eruda')");
};

/**
 * 引入eruda并初始化
 */
const insertErudaInit = (code: string): string => {
  const initCode = `
    import eruda from 'eruda';
    eruda.init();
  `;
  return code + initCode;
};

/**
 * 检查是否为入口文件
 */
const checkIsEntry = (id: string, entry?: string): boolean => {
  if (entry) return id.endsWith(entry);
  return !!id.match(/src\/main\.(js|jsx|ts|tsx)$/);
};
/**
 * 基于本地 eruda 的 vite插件
 */
const vitePluginErudaLocal = (options: { entry?: string } = {}) => {
  return {
    name: 'vite-plugin-eruda-local',
    transform(code: string, id: string) {
      if (
        process.env.NODE_ENV !== 'production' &&
        checkIsEntry(id, options.entry) &&
        !checkErudaImport(code)
      ) {
        return insertErudaInit(code);
      }
      return code;
    },
    configResolved(config: ResolvedConfig) {
      console.log(JSON.stringify(config))
    }, async buildStart() {
      const manifest = JSON.parse(await fs.promises.readFile('dist/manifest.json', 'utf-8'))
      const entryFile = manifest['index.html']['file']
      console.log('Entry file:', entryFile)
    },
  };
};

export default vitePluginErudaLocal;
